import datetime

import requests

import importlib


def dynamic_import(model_name, *attr):
    model = importlib.import_module(model_name)
    cls = []
    for _ in attr:
        if hasattr(model, _):
            cls.append(getattr(model, _))
        else:
            raise AttributeError("%s.%s" % (model_name, _))
    return cls[0] if len(attr) == 1 else cls


def local_time() -> datetime.datetime:
    """获取本地系统时间,可通过手动设置系统时间"""
    return datetime.datetime.now()


def net_time() -> datetime.datetime:
    """获取网络时间(北京时间)"""
    hea = {'User-Agent': 'Mozilla/5.0'}
    url = r'http://time1909.beijing-time.org/time.asp'
    r = requests.get(url=url, headers=hea)
    if r.status_code == 200:
        result = r.text
        data = result.split(";")
        year = data[1][len("nyear") + 3: len(data[1])]
        month = data[2][len("nmonth") + 3: len(data[2])]
        day = data[3][len("nday") + 3: len(data[3])]
        hrs = data[5][len("nhrs") + 3: len(data[5])]
        minute = data[6][len("nmin") + 3: len(data[6])]
        sec = data[7][len("nsec") + 3: len(data[7])]
        time_str = "%s-%s-%s %s:%s:%s" % (year, month, day, hrs, minute, sec)
        return datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
